import { goodsList, removeRule, addRule, getGoodsGroup, goodsGroup, queryGoodsCategory, changeStatus, addGoodsGroup, goodsCopy, shopList, getBindArticleList, getUnbindArticle, searchArticle, getBindArticle } from '../services/api';
import { message } from 'antd';
import G from '../utils/g';

export default {
  namespace: 'goodsList',

  state: {
    group: [],
    category: [],
    data: {
      list: [],
      pagination: {},
    },
    shopList : [],
    bindArticleList : [],
    bindArticleGoods: {}, // 绑定文章的商品详情
    searchArticleList: [], // 根据标题搜索文章列表，用于选择绑定文章
  },

  effects: {
    *fetch({ payload }, { call, put }) {
      const response = yield call(goodsList, payload);
      yield put({
        type: 'save',
        payload: {data : response},
      });
    },
    *fetchSearchArticle({ payload }, { call, put }) {
      const response = yield call(searchArticle, payload);
      if(response && response.articles){
        yield put({
          type: 'save',
          payload: {searchArticleList : response.articles},
        });
      }
    },
    *fetchBindArticleList({ payload }, { call, put }) {
      const response = yield call(getBindArticleList, payload);
      yield put({
        type: 'save',
        payload: {bindArticleList : response},
      });
    },
    *fetchUnbindArticle({ payload }, { call, put }) {
      const response = yield call(getUnbindArticle, payload);
      if(response){
        yield put({
          type: 'saveUnbindArticle',
          payload,
        });
      }
      return response;
    },
    *bindArticle({ payload }, { call, put }) {
      const response = yield call(getBindArticle, payload);
      if(response){
        return response;
      }

    },
    *getCategory({ payload }, { call, put }){
      const res = yield call(queryGoodsCategory, payload);
      if(res){
        yield put({
          type: 'save',
          payload : {category : res}
        });
      }
    },
    *getGroup({ payload }, { call, put }){
      const res = yield call(getGoodsGroup, payload);
      if(res){
        yield put({
          type: 'save',
          payload : {group : res}
        });
      }
    },
    *goodsGroup({ payload }, { call, put }){
      const res = yield call(goodsGroup, payload);
      if(res){
        yield put({
          type: 'saveGroup',
          payload : payload
        });
        message.success('分组成功！');
      }
    },
    *getShopList({ payload }, { call, put }){
      const res = yield call(shopList, payload);
      if(res){
        yield put({
          type: 'save',
          payload : {
            shopList : res
          }
        });
      }
    },
    *addGroup({ payload }, { call, put }){
      const res = yield call(addGoodsGroup, payload);
      if(res){
        yield put({
          type: 'saveAddGroup',
          payload : res
        });
        message.success('新增成功！');
      }
    },
    *changeStatus({ payload }, { call, put }){
      const res = yield call(changeStatus, payload);
      if(res){
        yield put({
          type: 'saveChangeStatus',
          payload : payload
        });
      }
    },
    *copy({ payload }, { call, put }){ //复制商品
      const res = yield call(goodsCopy, payload);
      if(res){
        yield put({
          type: 'saveCopy',
          payload : {
            id : payload.id,
            newId: res.id
          }
        });
        message.success('复制成功！');
      }
    },
    *add({ payload, callback }, { call, put }) {
      const response = yield call(addRule, payload);
      yield put({
        type: 'save',
        payload: response,
      });
      if (callback) callback();
    },
    *remove({ payload, callback }, { call, put }) {
      const response = yield call(removeRule, payload);
      yield put({
        type: 'save',
        payload: response,
      });
      if (callback) callback();
    },
  },

  reducers: {
    save(state, { payload }){
      return {
        ...state,
        ...payload
      }
    },
    saveUnbindArticle(state, {payload}){
      const { bindArticleList } = state;
      const rest = bindArticleList.filter(v=>v.id !== payload.articleId);
      return {
        ...state,
        bindArticleList : rest
      }
    },
    saveGroup(state, { payload }){
      let { ids, groups } = payload;
      ids = ids.split(',');
      groups = groups.split(',');
      console.log('a');
      let data = {...state.data};
      data.list.forEach(v=>{
        ids.forEach(val=>{
          if(v.id == val){  //id相等
            let temp = [];
            state.group.forEach(g=>{
              groups.forEach(gs=>{
                if(gs == g.name){
                  temp.push(g.name);
                }
              })
            });
            v.groups = temp;
          }
        });
      });
      return {
        ...state,
        ...{data : data}
      }
    },
    saveAddGroup(state, { payload }){
      let group = [...state.group];
      group.push(payload);
      return {
        ...state,
        group
      }
    },
    saveChangeStatus(state, { payload }){
      let { ids, status } = payload;
      ids = ids.split(',');
      let data = {...state.data};
      if(status == -1){ //删除
        ids.forEach(id=>{
          data.list.forEach((v,i)=>{
            if(v.id == id){
              data.list.splice(i,1);
            }
          });
        })
        message.success('删除成功！');
      }else{ //上下架
        data.list.forEach((v,i)=>{
          ids.forEach(val=>{
            if(v.id == val){  //id相等
              v.status = status;
            }
          });
        });
        message.success('修改成功！');
      }
      return {
        ...state,
        ...{data:data}
      }
    },
    saveCopy(state, { payload }){
      let data = {...state.data};
      const { id, newId } = payload;
      for(let i = 0; i < data.list.length; i++){
        if(data.list[i].id == id){
          let newItem = {
            ...data.list[i],
            id : newId,
            status: 0,//下架状态
            createTime: G.formAtTime(),
            updateTime: G.formAtTime()
          };
          data.list.splice(i, 0, newItem);
          break;
        }
      }
      return {
        ...state,
        ...{data:data}
      }
    },
    saveBindArticle(state, {payload}){
      const bindArticleList = [...state.bindArticleList];
      bindArticleList.unshift(payload);
      return {
        ...state,
        bindArticleList
      }
    }
  },
};
